package com.x.client

import android.content.Context
import android.support.annotation.Keep
import android.support.multidex.MultiDex
import com.socks.library.KLog
import com.taobao.sophix.PatchStatus
import com.taobao.sophix.SophixApplication
import com.taobao.sophix.SophixEntry
import com.taobao.sophix.SophixManager

/**
 * Creator : GG
 * Date    : 2018/6/11
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
class SophixStubApplication : SophixApplication() {


    private val TAG = "SophixStubApplication"

    // 此处SophixEntry应指定真正的Application，并且保证RealApplicationStub类名不被混淆。
    @Keep
    @SophixEntry(App::class)
    internal class RealApplicationStub

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        //如果需要使用MultiDex，需要在此处调用。
        MultiDex.install(this)
        initSophix()
    }

    private fun initSophix() {
        var appVersion = "0.0.0"
        try {
            appVersion = this.packageManager
                    .getPackageInfo(this.packageName, 0)
                    .versionName
        } catch (e: Exception) {
        }

        val instance = SophixManager.getInstance()
        instance.setContext(this)
                .setAppVersion(appVersion)
                .setSecretMetaData(getFixAppKey(), getFixAppSecret(), getFixRsa())
                .setEnableDebug(true)
                .setEnableFullLog()
                .setPatchLoadStatusStub { mode, code, info, handlePatchVersion ->
                    KLog.w("mode", mode)
                    KLog.w("code", code)
                    KLog.w("info", info)
                    KLog.w("handlePatchVersion", handlePatchVersion)

                    when (code) {
                        PatchStatus.CODE_LOAD_SUCCESS -> {
                            KLog.w(TAG, "sophix load patch success!")
                        }
                        PatchStatus.CODE_LOAD_RELAUNCH -> {// 如果需要在后台重启，建议此处用SharePreference保存状态。
                            KLog.w(TAG, "sophix preload patch success. restart app to make effect.")
                        }
                    }
                }.initialize()
    }

    fun getFixAppSecret() = getString(R.string.fix_app_secret) ?: ""

    fun getFixAppKey() = getString(R.string.fix_app_key) ?: ""

    fun getFixRsa() = getString(R.string.fix_rsa) ?: ""

}